package org.jmh.gift.rocketmq.listener.trans;

import com.alibaba.fastjson.JSONArray;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.jmh.gift.constants.GiftConstants;
import org.jmh.gift.dto.OffsaleDto;
import org.jmh.gift.service.IGoodsSpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 礼物上架的本地事务监听器
 */
@Component
@RocketMQTransactionListener(txProducerGroup = GiftConstants.GIFT_OFFSALE_TX_PRODUCER_GROUP)
public class OffsaleLocalTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IGoodsSpuService goodsSpuService;

    /**
     * 执行本地事务
     * @param msg
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        //1 获取消息内容
        byte[] payload = (byte[]) msg.getPayload();
        String s = new String(payload);
        List<OffsaleDto> OffsaleDtos = JSONArray.parseArray(s, OffsaleDto.class);

        //2 执行本地事务相关操作-修改数据库状态,添加日志,添加详情静态页
        // 将相关操作封装到service,它只要不报错就说明相关操作执行成功
        try {
            goodsSpuService.executeOffsaleLocalTransactionOpr(OffsaleDtos);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RocketMQLocalTransactionState.ROLLBACK;
    }

    /**
     * 回查本地事务
     * @param msg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        // 1 获取消息内容
        byte[] payload = (byte[]) msg.getPayload();
        String s = new String(payload);
        List<OffsaleDto> OffsaleDtos = JSONArray.parseArray(s, OffsaleDto.class);

        // 2 获取当前本地事务执行结果,根据本地事务执行结果返回
        try {
            // 回查本地事务,一定要给我返回本地事务执行结果  true:本地事务执行成功  false:本地事务执行失败
            Boolean flag = goodsSpuService.checkExsitOffsaled(OffsaleDtos);
            if(flag){
                return RocketMQLocalTransactionState.COMMIT;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
